package com.gzt.bookcatalog.dto;


import lombok.Data;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

@Data
public class PageParamDTO {


    private int page = 0;
    private int size = 10;
    private String sortField = "id";
    private String sortDirection = "desc";


    /**
     * 将 PageParam 转换为 Spring Data 的 Pageable 对象。
     * @return Pageable 对象
     */
    public Pageable toPageable() {
        if (sortField == null || sortField.trim().isEmpty()) {
            // 若 sortField 为空，不进行排序
            return PageRequest.of(page, size);
        }

        Sort.Direction direction = null;
        if (sortDirection != null && !sortDirection.trim().isEmpty()) {
            // 若 sortDirection 不为空，尝试解析排序方向
            direction = Sort.Direction.fromOptionalString(sortDirection.trim())
                    .orElse(Sort.Direction.DESC);
        } else {
            // 若 sortDirection 为空，使用默认降序
            direction = Sort.Direction.DESC;
        }

        return PageRequest.of(page, size, Sort.by(direction, sortField));
    }
}
